package org.tgcloud.group.core;

import org.springframework.stereotype.Component;
import org.tgcloud.group.entity.MjBusinessPerson;
import org.tgcloud.group.entity.SysManagerUser;

import java.security.MessageDigest;
import java.security.SecureRandom;

/**
 * Created by cloudLiu on 2015/8/7.
 */
@Component
public class PasswordHelper {

    private String algorithmName = "md5";
    private int hashIterations = 2;
    private int defaultNextBytesSize = 16;
    private static final char[] DIGITS = {
            '0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
    };


//    public void encryptPasswordAppUser(WorkNormalUser user) {
//
////    	设置一个自动生成的盐
//    	user.setSalt(generatorSalt());
////		根据明文密码、身份认证盐、加密算法、加密次数来算出加密的密码，与CredentialMatcher一致
//        String newPassword = generatorPass(
//                algorithmName,
//                user.getPassword(),
//                user.getSalt(),
//                hashIterations);
//
//        user.setPassword(newPassword);
//    }

//    public boolean checkAppUserPassIsCorrect(WorkNormalUser user, String password)
//    {
//        String newPassword = generatorPass(
//                algorithmName,
//                password,
//                user.getSalt(),
//                hashIterations);
//        return newPassword.equals(user.getPassword());
//
//    }

    public static String encodeToString(byte[] bytes) {
        int l = bytes.length;

        char[] out = new char[l << 1];

        // two characters form the hex value.
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = DIGITS[(0xF0 & bytes[i]) >>> 4];
            out[j++] = DIGITS[0x0F & bytes[i]];
        }
        char[] encodedChars = out;
        return new String(encodedChars);
    }

    private String generatorPass(String algorithmName, String originPass, String salt, int hashIterations) {
        try {
            byte[] saltBytes = salt.getBytes("utf-8");
            byte[] sources = originPass.getBytes("utf-8");
            MessageDigest digest = MessageDigest.getInstance(algorithmName);
            if (saltBytes != null) {
                digest.reset();
                digest.update(saltBytes);
            }
            byte[] hashed = digest.digest(sources);
            int iterations = hashIterations - 1; //already hashed once above
            //iterate remaining number:
            for (int i = 0; i < iterations; i++) {
                digest.reset();
                hashed = digest.digest(hashed);
            }
            return encodeToString(hashed);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String generatorSalt()
    {
        byte[] bytes = new byte[defaultNextBytesSize];
        new SecureRandom().nextBytes(bytes);
        return encodeToString(bytes);
    }


    public boolean checkManagerPassIsCorrect(SysManagerUser user, String password)
    {
        String newPassword = generatorPass(
                algorithmName,
                password,
                user.getSalt(),
                hashIterations);
        return newPassword.equals(user.getPassword());

    }

    public void encryptPasswordManagerUser(SysManagerUser user) {

//    	设置一个自动生成的盐
        user.setSalt(generatorSalt());
//		根据明文密码、身份认证盐、加密算法、加密次数来算出加密的密码，与CredentialMatcher一致
        String newPassword = generatorPass(
                algorithmName,
                user.getPassword(),
                user.getSalt(),
                hashIterations);

        user.setPassword(newPassword);
    }

    public boolean checkBusinessPassIsCorrect(MjBusinessPerson user, String password)
    {
        String newPassword = generatorPass(
                algorithmName,
                password,
                user.getSalt(),
                hashIterations);
        return newPassword.equals(user.getPassword());

    }

    public void encryptPasswordBusinessUser(MjBusinessPerson user) {

//    	设置一个自动生成的盐
        user.setSalt(generatorSalt());
//		根据明文密码、身份认证盐、加密算法、加密次数来算出加密的密码，与CredentialMatcher一致
        String newPassword = generatorPass(
                algorithmName,
                user.getPassword(),
                user.getSalt(),
                hashIterations);

        user.setPassword(newPassword);
    }
}
